<!-- 支付页面 待审核 -->
<template>
  <view class="body">
    <view class="pay_box">
      <view class="header">
        <view class="price">￥{{ allPay }}</view>
        <view class="tips">请您扫码付款</view>
        <view class="img">
          <image class="icon" src="../../assets/images/pages2/pay/icon1.png"></image>
          <image class="icon" src="../../assets/images/pages2/pay/icon2.png"></image>
          <image class="icon" src="../../assets/images/pages2/pay/icon3.png"></image>
        </view>
      </view>
      <!-- 二维码 -->
      <view class="code_box">
        <view v-if="codeUrl">
          <!-- <qrCode :text="codeUrl" :qrWidth="400"></qrCode> -->
          <qrCode :text="codeUrl" :qrWidth="400" @getImgUrl="handleGetImgUrl"></qrCode>
          <!-- <view class="update_tips">15分钟内有效，点击<span @click="update" class="update">刷新</span></view> -->
          <view class="update_tips">{{ formatTime }}<span @click="update" class="update">刷新</span></view>
          <view class="btn" @click="saveImage">保存到相册</view>
        </view>
        <view v-else class="tips">二维码获取失败</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import Taro, { useReady, useRouter } from '@tarojs/taro'
import { onMounted, ref, nextTick, reactive, onBeforeUnmount,computed } from 'vue'
import qrCode from '@/components/qrcode2/index.vue'
import useOrderStore from '@/store/order'
import useUserStore from '@/store/user'
import picker from '@/store/pick'

import { getupdateRemarks } from '@/@api/review' // 审核订单接口
import { pickGoods } from '@/@api/sign' // 我要交货接口
import { getReckLogBatch } from '@/@api/waybill' // 支付前的接口
import { NewPayParam, getPaySrc, payResult } from '@/@api/order' // 获取支付二维码 支付成功回调接口
import { shBaseUrl } from '@/@api/urls'
const userStore = useUserStore()

const router = useRouter()

const orderStore = useOrderStore()
const orderList = ref<any>()
orderList.value = orderStore.orderInfo

const pickStore = picker()
console.log(pickStore.pickerData, '仓库里的pickerData')

const codeUrl = ref('') // 二维码url
const timer = ref() // 定时器

const billFlag = ref() // 到底是哪个页面来的 待审核 待提货 待支付

const needPay = ref(0) // 计算出的待付款
const allPay = ref(0) // 总金额 待付款+保管费

// 二维码之前的参数
const beforeParams = {
  billNoArr: [orderList.value.billNo],
  manageFee: []
}

const imgUrl = reactive({ url: '' }) // 二维码图片url

useReady(() => {
  Taro.setNavigationBarTitle({
    title: '支付收银台'
  })
  Taro.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: '#0966FF'
  })
})

onMounted(() => {
  Taro.authorize({
    scope: 'scope.writePhotosAlbum',
    success() {
      console.log('获取权限成功')
    },
    fail() {
      console.log('获取权限失败')
    }
  })
  countPay() // 计算总金额
  getCodeBefore() // 二维码前先调这个
})

onBeforeUnmount(() => {
  if (timer.value != null) {
    clearTimeout(timer.value)
  }
  clearInterval(Mintimer)
})

const remainingTime = ref(900) // 初始剩余秒数
const expired = ref(false) // 是否过期
let Mintimer

const formatTime = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60)
  const seconds = remainingTime.value % 60
  return `${minutes} 分钟 ${seconds} 秒`
})

const startTimer = () => {
  console.log('倒计时')
  Mintimer = setInterval(() => {
    if (remainingTime.value <= 0) {
      expired.value = true
      clearInterval(Mintimer)
    } else {
      remainingTime.value--
    }
  }, 1000)
}

// 计算待支付费用 判断订单类型
function countPay() {
  orderStore.orderInfo.costList.forEach((t) => {
    let difference = t.actualMoney - t.paidMoney
    needPay.value += difference
  })
  console.log(router, 'router')
  const { saveMoney, fromPage } = router.params
  billFlag.value = fromPage
  if (saveMoney) {
    console.log(router.params, '传来的是啥')
    allPay.value = Number(needPay.value) + Number(saveMoney)
  } else {
    allPay.value = Number(needPay.value)
  }
}

async function getCodeBefore() {
  const { data } = await getReckLogBatch(beforeParams)
  if (data.code == 200) {
    // 获取支付二维码
    reqGetPaySrc()
  } else {
    codeUrl.value = ''
  }
}

// 获取图片url
function handleGetImgUrl(img) {
  console.log(img, '获取子传父的url')
  nextTick(() => {
    imgUrl.url = img
  })
}

// 保存相册
function saveImage() {
  console.log(imgUrl.url, '保存到相册')
  Taro.saveImageToPhotosAlbum({
    filePath: imgUrl.url,
    success() {
      Taro.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    },
    fail() {
      Taro.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 刷新二维码
function update() {
  codeUrl.value = ''
  reqGetPaySrc()
}

// 获取支付二维码
async function reqGetPaySrc() {
  const params = {
    bill: {
      billNos: [orderList.value.billNo],
      // "money": allPay.value,
      // "actualMoney": allPay.value,
      money: '0.01',
      actualMoney: '0.01',
      serviceCharge: 0,
      btssId: 1,
      manage_fee: []
    },
    device_info: 'pp01',
    body: '支付运单3',
    attach: '000003069',
    // "total_fee": allPay.value * 100,
    total_fee: 1,
    branchno: '00002',
    paytype: '04',
    eop: 'SYSADMIN',
    type: '01',
    v3: '',
    isdebug: 'True',
    debug: true
  }
  const { data } = await getPaySrc(params)
  if (data.code == 200) {
    let orderId = JSON.parse(data.data).ORDERID
    codeUrl.value = JSON.parse(data.data).QRCODESTRING
    // 二维码出来了开始倒计时
    startTimer
    payReturn(orderId)
    // payTaro(orderId)
  } else {
    console.log('获取二维码失败')
  }
}

// 支付回调
async function payReturn(e) {
  clearTimeout(timer.value)
  const res = await payResult({ orderid: e })
  if (res.data.code == 200) {
    let data = JSON.parse(res.data.data.data)[0]
    if (data.STATUSCODE && data.STATUSCODE == '1') {
      clearTimeout(timer.value)
      // 通过传参来判断是 审核 提货 待支付
      switch (billFlag.value) {
        case 'review':
          toReview()
          break
        case 'sign':
          pickGood()
          break
        default:
          console.log('其他页面来的pay页面')
          break
      }
    } else {
      timer.value = setTimeout(() => {
        console.log('未支付成功')
        payReturn(e)
      }, 5000)
    }
  }
}

// 支付回调
// function payTaro(e) {
//   Taro.request({
//     url: shBaseUrl + '/selfmachine-system/fee/pay/result', //仅为示例，并非真实的接口地址
//     data: { orderid: e },
//     header: {
//       'content-type': 'application/json', // 默认值
//       Authorization: userStore.token,
//     },
//     success: function (res) {
//       // 隐藏加载状态
//       Taro.hideLoading();
//       if (res.data.code == 200) {
//         let data = JSON.parse(res.data.data.data)[0];
//         if (data.STATUSCODE && data.STATUSCODE == "1") {
//           clearTimeout(timer.value);
//           // 通过传参来判断是 审核 提货 待支付
//           switch (billFlag.value) {
//             case 'review':
//               toReview();
//               break;
//             case 'sign':
//               pickGood();
//               break;
//             default:
//               console.log('其他页面来的pay页面')
//               break;
//           }
//         } else {
//           timer.value = setTimeout(() => {
//             console.log('未支付成功');
//             payTaro(e)
//           }, 5000)
//         }
//       }
//     }
//   })
// }

// 调用审核接口审核订单
async function toReview() {
  const reviewParams = [
    {
      billNo: orderList.value.billNo,
      ssoId: orderList.value.ssoId,
      isExamine: 2,
      pickUpMode: orderList.value.pickUpMode
    }
  ]
  const { data } = await getupdateRemarks(reviewParams)
  if (data.code == 200) {
    console.log('审核成功')
    // 跳转审核详情页
    Taro.navigateTo({
      url: '/pages2/pay/info?billFlag=review'
    })
  }
}

// 交货接口
async function pickGood() {
  const pickParams = pickStore.pickerData
  console.log(pickParams, '交货接口入参')
  const { data } = await pickGoods(pickParams)
  if (data.code == 200) {
    console.log(data, '交货成功跳转交货成功详情页')
    Taro.navigateTo({
      url: `/pages2/pay/info?billFlag=sign`
    })
  }
}

// 调用支付接口
function toPayment() {
  console.log('支付成功直接跳转支付成功页')
  // 跳转收款成功详情页
  Taro.navigateTo({
    url: `/pages2/pay/info?billFlag=payment`
  })
}
</script>
<style lang="scss">
* {
  box-sizing: border-box;
}

.body {
  box-sizing: border-box;
  width: 100vw;
  height: 100%;
  position: relative;
  background-color: #0966ff;
  padding-bottom: 12rpx;
}

.pay_box {
  width: 702rpx;
  height: 1060rpx;
  background: url('../../assets/images/pages2/pay/pay_box.png');
  background-size: 100% 100%;
  margin: 0 auto;
  text-align: center;
  padding-top: 32rpx;

  .price {
    font-size: 76rpx;
    color: #252525;
  }

  .tips {
    font-size: 32rpx;
    color: #666;
  }

  .img {
    .icon {
      width: 160rpx;
      height: 80rpx;
    }
  }

  .update_tips {
    font-size: 22rpx;
    color: #000;
    margin: 16rpx auto;

    .update {
      color: #0966ff;
      text-align: center;
      display: inline-block;
    }
  }

  .btn {
    width: 480rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 200rpx;
    opacity: 1;
    border: 1rpx solid #0966ff;
    color: #0966ff;
    font-weight: bold;
    text-align: center;
    margin: 0 auto;
  }
}
</style>
